package com.zgw.his.design.resource;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocumentListener;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IPropertyListener;
import org.eclipse.ui.IWorkbenchPartConstants;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.FileEditorInput;

import com.zgw.his.design.editor.MedicalEditor;
import com.zgw.his.design.model.Folder;
import com.zgw.his.design.model.Template;
import com.zgw.his.design.resource.dialog.PreviewDialog;
import com.zgw.his.design.resource.ui.ResourceTreeUI;

@SuppressWarnings("restriction")
public class ResourceTree extends ResourceTreeUI {
	public static final String ID = "com.zgw.his.design.resource.ResourceTree";
	private MedicalResourceManager manager = new MedicalResourceManager();

	// =============================
	// Image
	// =============================

	@Override
	protected void doOpenResource() {
		Object selData;
		if (tree.getSelection().length > 0
				&& (selData = tree.getSelection()[0].getData()) instanceof Template) {
			final Template temp = (Template) selData;
			IFile tempFile = (IFile) temp.getResource();
			IEditorInput input = new FileEditorInput(tempFile);
			try {
				long start = System.currentTimeMillis();
				MedicalEditor editPpart = (MedicalEditor) getViewSite()
						.getWorkbenchWindow().getActivePage()
						.openEditor(input, MedicalEditor.ID);
				editPpart.showDesign();

				editPpart.setMedicalTemplate(temp);
				editPpart.setResourceManager(manager);
				initializeEditListener(editPpart);
				editPpart.refreshUI();
				System.out.println("耗时: "
						+ (System.currentTimeMillis() - start));
			} catch (PartInitException e) {
				e.printStackTrace();
			}
		}
	}

	private void initializeEditListener(final MedicalEditor editPpart) {

		editPpart.addPropertyListener(new IPropertyListener() {
			public void propertyChanged(Object source, int propId) {
				if (IWorkbenchPartConstants.PROP_PART_NAME == propId) {
					Rectangle re = findTreeItem(editPpart.getMedicalTemplate())
							.getBounds();
					tree.redraw(re.x, re.y, re.width, re.height, true);
				}
			}
		});

		editPpart.getDocument().addDocumentListener(new IDocumentListener() {
			public void documentChanged(DocumentEvent event) {
				Template temp = editPpart.getMedicalTemplate();
				if (temp.getState() == Template.STATE_NOMAL) {
					temp.setState(Template.STATE_UPDATE);
					try {
						// 设置 资源持久化属性
						temp.setPersistentProperty(temp.KEY_STATE,
								temp.STATE_UPDATE + "");
					} catch (CoreException e) {
						e.printStackTrace();
					}
				}
			}

			public void documentAboutToBeChanged(DocumentEvent event) {

			}
		});
	}

	@Override
	protected void doSubmit() {
		try {
			manager.save();
			tree.redraw();
			MessageDialog.openInformation(getSite().getShell(), "提示", "保存成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void doDelete() {
		Object sd = getSelectedData();
		boolean result = true;
		try {
			if (sd instanceof Template) {
				Template t = (Template) sd;
				result = MessageDialog.openQuestion(getViewSite().getShell(),
						"", "确认删除" + t.getName());
				if (result) {
					manager.deleteTemplate(t);
				}
			} else if (sd instanceof Folder) {
				Folder f = (Folder) sd;
				result = MessageDialog.openQuestion(getViewSite().getShell(),
						"", "确认删除" + f.getName());
				if (result) {
					manager.deleteFolder(f);
				}
			}
			if (result) {
				tree.getSelection()[0].dispose();
			}
		} catch (Exception e) {
			MessageDialog.openError(getViewSite().getShell(), "",
					"删除失败" + e.getMessage());
			e.printStackTrace();
		}
	}

	@Override
	protected void doPreview() {
		String path = "";
		if (tree.getSelection().length > 0
				&& tree.getSelection()[0].getData() instanceof Template) {
			path = ((Template) tree.getSelection()[0].getData()).getPath();
			path = Platform.getLocation().toString() + path;
		} else {
			return;
		}
		PreviewDialog dlg = new PreviewDialog(getViewSite().getShell(),
				SWT.NONE, path);
		dlg.open();
	}

	@Override
	protected Folder newFolder(TreeItem parent, String name) {
		Folder pf = null;
		if (parent != null && parent.getData() instanceof Folder) {
			pf = (Folder) parent.getData();
		}
		try {
			return manager.newFolder(pf, name);
		} catch (Exception e) {
			MessageDialog.openError(getViewSite().getShell(), "创建失败",
					e.getMessage());
			e.printStackTrace();
		}
		return null;
	}

	@Override
	protected Template newTemplate(TreeItem parent, String name) {
		Folder pf = null;
		if (parent != null && parent.getData() instanceof Folder) {
			pf = (Folder) parent.getData();
		}
		try {
			return manager.newTemplate(pf, name);
		} catch (Exception e) {
			MessageDialog.openError(getViewSite().getShell(), "创建失败",
					e.getMessage());
			e.printStackTrace();
		}
		return null;
	}

	// 构建资源树
	@Override
	public void buildTree() {
		super.buildTree();
		try {
			manager.synchronization();
			for (Folder f : manager.getRootFolders()) {
				buildSourceItem(f, null);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void buildSourceItem(Folder folder, TreeItem parent) {
		TreeItem item = null;
		if (!manager.isDefaultFolder(folder)) {
			item = super.createFolderItem(folder, parent);
			for (Folder child : folder.getChidren()) {
				buildSourceItem(child, item);
			}
		}
		for (Template t : folder.getTemplates()) {
			super.createFileItem(t, item);
		}
	}

	protected boolean redrawItem(GC gc, TreeItem item) {
		Image img = null;

		Object obj = item.getData();
		if (obj instanceof Template) {
			img = ((Template) obj).getState() == Template.STATE_NEW ? image_state_new
					: img;
			img = ((Template) obj).getState() == Template.STATE_UPDATE ? image_state_update
					: img;
			item.setText(((Template) obj).getName());
		} else if (obj instanceof Folder) {
			img = ((Folder) obj).getState() == Template.STATE_NEW ? image_state_new
					: img;
			img = ((Folder) obj).getState() == Template.STATE_UPDATE ? image_state_update
					: img;
			item.setText(((Folder) obj).getName());
		}
		boolean subUpdate = false; // 子节点是否修改
		for (TreeItem i : item.getItems()) {
			if (redrawItem(gc, i) || subUpdate) {
				subUpdate = true;
			}
		}
		if (img == null && subUpdate) {
			img = image_state_update;
		}
		if (img != null) {
			Rectangle r = item.getBounds();
			gc.drawImage(img, r.x - 7, r.y + r.height - 7);
			return true;
		}
		return false;

	}
}
